package cn.promonkey.api.dashboard.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.promonkey.core.dto.UserDto;
import cn.promonkey.core.response.ResultMsg;
import cn.promonkey.core.security.SecurityService;
import cn.promonkey.core.toolkit.QueryGenerator;
import cn.promonkey.core.toolkit.UserInfoUtils;
import cn.promonkey.api.group.entity.Group;
import cn.promonkey.api.group.service.GroupService;
import cn.promonkey.api.relation.entity.Relation;
import cn.promonkey.api.relation.service.RelationService;
import cn.promonkey.api.system.entity.System;
import cn.promonkey.api.system.service.SystemService;
import cn.promonkey.api.user.service.UserService;
import lombok.extern.slf4j.Slf4j;

import static org.mockito.ArgumentMatchers.anyCollection;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/** @author <no value> */
@Slf4j
@RestController
@RequestMapping("/dashboard/")
public class DashboardController {
  final SystemService systemService;
  
  final GroupService groupService;
  final RelationService relationService;
  
  public DashboardController(SystemService systemService,GroupService groupService,RelationService relationService) {
    this.systemService = systemService;
    this.groupService = groupService;
    this.relationService = relationService;
  }

  @RequestMapping("getDashboard")
  public String getDashboard(
      System system,
      @RequestParam(name = "page", defaultValue = "1") Integer page,
      @RequestParam(name = "size", defaultValue = "12") Integer size,
      HttpServletRequest request) {
    QueryWrapper<System> queryWrapper = QueryGenerator.initQueryWrapper(system, request.getParameterMap());
    UserDto userDto = UserInfoUtils.getUserInfo();//SecurityService.getCurrentUserAndCheck(null);
    QueryWrapper<Relation> relationWrapper = new QueryWrapper<>();
    relationWrapper.eq("user_id", userDto.getUserId());
    List<Relation> relationList = relationService.list(relationWrapper);
    List<Long> groups = relationList.stream().map(Relation::getGroupId).collect(Collectors.toList());
    
    QueryWrapper<Group> groupWrapper = new QueryWrapper<>();
    if(groups.size()>0) {
    	groupWrapper.in("group_id", groups);
    }else {
    	groupWrapper.eq("group_id", 0);
    }
    
    List<Group> groupList = groupService.list(groupWrapper);
    
    List<Long> systemList = groupList.stream().map(Group::getSystemId).collect(Collectors.toList());
    
    if(systemList.size()>0) {
    	queryWrapper.in("system_id", systemList);
    }else {
    	queryWrapper.eq("system_id", 0);
    }
    
    Page<System> pageable = new Page<>(page, size);
    IPage<System> pageList = systemService.page(pageable, queryWrapper);
    return ResultMsg.success(pageList);
  }
  
 
}
